import { ref } from 'vue';
import { getMerchantDetail, getProductDetail, getMerchantCategories } from '@/api/merchant';

export interface MerchantInfo {
  id: number;
  name: string;
  logo: string;
  coverImage: string;
  rating: number;
  sales: number;
  distance: number;
  minPrice: number;
  deliveryFee: number;
  deliveryTime: number;
  tags: string[];
  phone: string;
  address: string;
  businessHours: string;
  notice: string;
}

export interface Category {
  id: number;
  name: string;
  products: Product[];
}

export interface Product {
  id: number;
  name: string;
  description?: string;
  image: string;
  price: number;
  sales: number;
  tastes?: any[];
}

export function useMerchantData() {
  const merchantInfo = ref<MerchantInfo>({
    id: 0,
    name: '',
    logo: '',
    coverImage: '',
    rating: 0,
    sales: 0,
    distance: 0,
    minPrice: 0,
    deliveryFee: 0,
    deliveryTime: 0,
    tags: [],
    phone: '',
    address: '',
    businessHours: '',
    notice: ''
  });

  const categories = ref<Category[]>([]);
  const currentCategory = ref(0);

  // 加载商家数据
  const loadMerchantData = async (merchantId: number) => {
    try {
      uni.showLoading({ title: '加载中...' });
      
      const detail = await getMerchantDetail(merchantId.toString());
      
      merchantInfo.value = {
        id: merchantId,
        name: detail.merchantName || detail.name || '商家名称',
        logo: detail.avatarUrl || '/static/shangjia01.png',
        coverImage: detail.avatarUrl || '/static/food01.png',
        rating: detail.rating || 4.8,
        sales: detail.salesCount || 0,
        distance: 1.2, // 需要通过经纬度计算
        minPrice: detail.minOrderAmount || 20,
        deliveryFee: detail.deliveryFee || 3,
        deliveryTime: detail.estimatedDeliveryTime || 30,
        tags: detail.tags ? detail.tags.split(',') : [],
        phone: detail.contactPhone || '',
        address: detail.address || '',
        businessHours: detail.businessHours || '09:00 - 21:00',
        notice: detail.notice || '欢迎光临'
      };
      
      await loadCategories(merchantId);
      
      uni.hideLoading();
    } catch (error) {
      uni.hideLoading();
      console.error('加载商家数据失败:', error);
      uni.showToast({ 
        title: '加载失败',
        icon: 'none' 
      });
      throw error;
    }
  };

  // 加载分类和商品
  const loadCategories = async (merchantId: number) => {
    try {
      const data = await getMerchantCategories(merchantId.toString());
      
      if (!Array.isArray(data)) {
        console.warn('分类数据格式异常:', data);
        categories.value = [];
        return;
      }
      
      // 映射后端数据到前端格式
      categories.value = data.map((cat: any) => ({
        id: cat.categoryId,
        name: cat.categoryName || cat.name || '未知分类',
        products: (cat.products || []).map((prod: any) => ({
          id: prod.productId,
          name: prod.name || '未知商品',
          description: prod.description || '',
          image: prod.imageUrl || prod.image || '/static/food01.png',
          price: prod.regionPrice || prod.price || 0,
          sales: prod.salesCount || prod.salesVolume || 0,
          tastes: prod.tastes || [] // 保存口味选项用于规格选择
        }))
      }));
      
      console.log('✅ 分类和商品加载成功:', categories.value);
      
    } catch (error) {
      console.error('加载分类失败:', error);
      categories.value = [];
      uni.showToast({
        title: '加载商品失败',
        icon: 'none'
      });
    }
  };

  // 选择分类
  const selectCategory = (index: number) => {
    currentCategory.value = index;
  };

  // 检查商品是否有规格
  const checkProductSpecs = async (productId: number) => {
    try {
      // 先从已加载的分类中查找商品
      for (const category of categories.value) {
        const product = category.products.find((p: Product) => p.id === productId);
        if (product) {
          // 如果商品有tastes字段且不为空，说明有规格
          const hasTastes = product.tastes && product.tastes.length > 0;
          console.log(`商品${productId}规格检查:`, hasTastes ? '有规格' : '无规格', product.tastes);
          return hasTastes;
        }
      }
      
      // 如果在分类中找不到，再调用API（备用方案）
      console.log(`商品${productId}未在分类中找到，调用API查询...`);
      const detail = await getProductDetail(productId.toString());
      return detail.tastes && detail.tastes.length > 0;
      
    } catch (error) {
      console.error('检查商品规格失败:', error);
      return false;
    }
  };

  return {
    merchantInfo,
    categories,
    currentCategory,
    loadMerchantData,
    selectCategory,
    checkProductSpecs
  };
}